package gui.visu.components;

import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.Iterator;
import java.util.SortedMap;

import javax.swing.JPanel;

import controls.visu.TimeLadderControl;
import data.Constants;
import data.visu.structures.TimeTick;



/**
 * @author Charles Perin
 * 29 mars 2011
 * LIMSI - INRIA Rennes
 * charles.perin@free.fr
 *
 */
public class TimePanel extends JPanel{

	/**
	 * 
	 */
	private static final long serialVersionUID = 41604743888547437L;

	private SortedMap<Integer, TimeTick> timeTicksInTable;
	private TimeLadderControl controler;

	public TimePanel() {
		this.setBackground(Constants.TIME_LADDER_BACKGROUND_COLOR_DEFAULT);
	}

	@Override
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		g.setColor(Color.BLACK);
		g.drawLine(0, this.getHeight()-1, this.getWidth(), this.getHeight()-1);
		Iterator<Integer> iter = timeTicksInTable.keySet().iterator();
		while(iter.hasNext()){
			int currentFrame = iter.next();
			TimeTick tick = timeTicksInTable.get(currentFrame);
			drawStringValue(g,tick);
			int xValueOnRef = translateValueOnGoodCurveSideForCurves(tick.getxValueOnRef());
			g.drawLine(xValueOnRef, this.getHeight(), xValueOnRef, this.getHeight()-3);
		}
	}
	
	public int translateValueOnGoodCurveSideForCurves(int value){
		double verticalCut = this.getBounds().getWidth()/3;
		if(value>verticalCut) return (int)(value+verticalCut);
		else return value;
	}
	
	private void drawStringValue(Graphics g, TimeTick tick){
		String[] value = TimeLadderControl.frame2HMSInTab(tick.getFrame());
		if(value[2].equals("0")){
			if(value[1].equals("0")){
				g.setFont(Constants.TIME_PANEL_FONT_HOURS);
			}
			else{
				g.setFont(Constants.TIME_PANEL_FONT_MINUTES);
			}
		}
		else{
			g.setFont(Constants.TIME_PANEL_FONT_SECONDS);
		}
		
		FontMetrics fm = g.getFontMetrics ();
		int value_width = fm.stringWidth (tick.getHMSString());
		int xValueOnRef = translateValueOnGoodCurveSideForCurves(tick.getxValueOnRef());
		int value_x = (int) (xValueOnRef - value_width/2);
		int value_y = this.getHeight() - 3-(8-tick.getLevel());
		if(value_x<0)value_x=0;
		else if(value_x+value_width>this.getWidth())value_x=this.getWidth()-value_width;
		g.drawString (tick.getHMSString(), value_x, value_y);
	}

	public void setTimeLadderParams(SortedMap<Integer, TimeTick> ticksDisplayed) {
		this.timeTicksInTable=ticksDisplayed;
	}

	public void setControler(TimeLadderControl controler) {
		this.controler = controler;
	}

	public TimeLadderControl getControler() {
		return controler;
	}
}
